package com.sita.cfmoto.services;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.sita.cfmoto.R;
import com.sita.cfmoto.persistence.User;
import com.sita.cfmoto.support.Constants;
import com.sita.cfmoto.utils.PersistUtils;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Class com.sita.bike.services is for
 *
 * @author xiaodong on 15/4/19.
 */
public class XmppBackgroundService extends Service {
    private static final String LOG_TAG = XmppBackgroundService.class.getSimpleName();

    private XmppServiceBinder binder;
    private ExecutorService executorService = Executors.newCachedThreadPool();
    private User person;

    @Override
    public void onCreate() {
        super.onCreate();
        binder = new XmppServiceBinder(this);
        person = PersistUtils.getCurrentUser();
        Log.d(LOG_TAG, "XmppBackgroundService onCreate");
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(LOG_TAG, "onStartCommand");

        executorService.execute(new ConnectWorkerThread());

        startForground();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
//        executorService.execute(new DisconnectWorkerThread(imClient));
        executorService.shutdown();
        try {
            executorService.awaitTermination(Constants.TIMEOUT, TimeUnit.MILLISECONDS);
            executorService = null;
        } catch (InterruptedException e) {
        }
        stopForeground(true);
        super.onDestroy();
    }

    private void updateNickName() {

    }

    private void startForground() {
        Intent intent = new Intent(this, XmppBackgroundService.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendIntent = PendingIntent.getService(this, 0, intent, 0);

        Bitmap icon = BitmapFactory.decodeResource(this.getResources(),
                R.mipmap.ic_launcher);
        Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(icon)
                .setContentIntent(pendIntent)
                .build();
        notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
        startForeground(0, notification);

    }

//    private class DisconnectWorkerThread implements Runnable {
//        private XmppIMClient xmppIMClient;
//
//        DisconnectWorkerThread(XmppIMClient client) {
//            xmppIMClient = client;
//        }
//
//        @Override
//        public void run() {
//            xmppIMClient.disconnect();
//        }
//    }

    private class XmppServiceBinder extends Binder {
        private XmppBackgroundService mService;

        public XmppServiceBinder(XmppBackgroundService service) {
            super();
            mService = service;
        }

        public XmppBackgroundService getService() {
            return mService;
        }
    }

    private class ConnectWorkerThread implements Runnable {

        ConnectWorkerThread() {
        }

        @Override
        public void run() {
            EMClient.getInstance().login(
                    person.getXmppUser(),
                    person.getXmppPass(),
                    new EMCallBack() {

                        @Override
                        public void onSuccess() {
//                            // 登陆成功，保存用户名
////                            FriendHelper.getInstance().setCurrentUserName(person.getXmppUser());
//                            // 注册群组和联系人监听
//                            FriendHelper.getInstance().registerGroupAndContactListener();

//                            // update nick name
//                            EMChatManager.getInstance().updateCurrentUserNick(
//                                    (person.person.getName() == null) ?
//                                            person.person.getMobile() : person.person.getName());
//                            // ** 第一次登录或者之前logout后再登录，加载所有本地群和回话
//                            // ** manually load all local groups and
//                            EMGroupManager.getInstance().loadAllGroups();
//                            EMChatManager.getInstance().loadAllConversations();

                            // TODO: 2015/12/14 update nickname
//
//                            // 更新当前用户的nickname 此方法的作用是在ios离线推送时能够显示用户nick
//                            boolean updatenick = EMChatManager.getInstance().updateCurrentUserNick(
//                                    DemoApplication.currentUserNick.trim());
//                            if (!updatenick) {
//                                Log.e("LoginActivity", "update current user nick fail");
//                            }
                            // TODO: 2015/12/14 update header
//                            //异步获取当前用户的昵称和头像(从自己服务器获取，demo使用的一个第三方服务)
//                            FriendHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();

                        }

                        @Override
                        public void onError(int i, String s) {

                        }

                        @Override
                        public void onProgress(int i, String s) {

                        }
                    }
            );
        }
    }
}
